package com.vr.cloudpicture.manager.websocket.strategy.impl;

import cn.hutool.core.bean.BeanUtil;
import com.vr.cloudpicture.manager.websocket.handler.PictureEditBroadcast;
import com.vr.cloudpicture.manager.websocket.handler.PictureEditingStatusManager;
import com.vr.cloudpicture.manager.websocket.model.PictureEditRequestMessage;
import com.vr.cloudpicture.manager.websocket.model.PictureEditResponseMessage;
import com.vr.cloudpicture.manager.websocket.model.enums.PictureEditMessageTypeEnum;
import com.vr.cloudpicture.manager.websocket.strategy.PictureEditMessageStrategy;
import com.vr.cloudpicture.model.dto.user.UserLogin;
import com.vr.cloudpicture.model.vo.UserVO;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * 进入图片编辑状态处理的策略
 *
 * @author hzh
 * @date 2025/05/28
 */
@Component
public class EnterEditMessageStrategy implements PictureEditMessageStrategy {
    @Override
    public void handle(PictureEditRequestMessage requestMessage, WebSocketSession session, UserLogin user, Long pictureId) throws Exception {
        // 图片没有被编辑时,才能进入编辑状态
        if (!PictureEditingStatusManager.isBeingEdited(pictureId)) {
            // 设置当前用户为此图片的编辑用户
            PictureEditingStatusManager.setEditingUser(pictureId, user.getId());
            // 构建响应
            PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
            responseMessage.setType(PictureEditMessageTypeEnum.ENTER_EDIT.getValue());
            String message = String.format("%s开始编辑图片", user.getUserName());
            responseMessage.setMessage(message);
            responseMessage.setUser(BeanUtil.toBean(user, UserVO.class));
            // 广播通知给同一张图片的所有用户
            PictureEditBroadcast.broadcastToPicture(pictureId, responseMessage);
        }
    }
}
